<script lang="ts" setup>
import { getCodeOrdersApi, postCodeOrderApi } from '@/pagesBreakfast/services/pagesBreakfast'
import { useMemberStore, usePhoneStore } from '@/stores'
import type { listType } from '@/types/pagesBreakfast'
import { PageSkip, Toast, extractQueryParams } from '@/utils/tools'
import { onLoad, onReady, onShow } from '@dcloudio/uni-app'
import { computed, ref, watch } from 'vue'

const memberStore = useMemberStore()
const phoneStore = usePhoneStore()
const BjsPopupRef = ref()
const formRef = ref()

const formParams = ref({
  enterpriseId: 0,
  enterpriseName: '',
  remark: '',
  orderSn: '',
  type: 0,
})

const enterpriseObj = computed(() => {
  if (formParams.value.type === 1) {
    return {
      enterpriseName: '公司',
      remark: '工位号',
    }
  } else {
    return {
      enterpriseName: '酒店',
      remark: '房间号',
    }
  }
})

const list = ref<any>([])
const rules = computed(() => ({
  remark: {
    rules: [{ required: true, errorMessage: `您的${enterpriseObj.value.remark}必填` }],
  },
}))
const parasmsList = ref<listType[]>([])
const numLength = computed(() => {
  const sum = list.value.reduce((prev: number, next: any) => {
    return prev + next.selectedNum
  }, 0)
  return 2 - sum
})
const _disabled = computed(() => {
  const sum = list.value.reduce((prev: number, next: any) => {
    return prev + next.selectedNum
  }, 0)
  return Number(sum) > 0 ? false : true
})
const changeValue = (item: any, type: boolean) => {
  if (type) {
    if (!numLength.value) return
    const hasExistingItem = parasmsList.value.some((listItem) => {
      return listItem.id === item.id
    })
    if (hasExistingItem && item.comboSurplusNum > item.selectedNum) {
      console.log('+++++++')
      parasmsList.value.forEach((ev) => {
        if (ev.id === item.id) {
          ev.comboNum++
          item.selectedNum++
        }
      })
      console.log(parasmsList.value)
    } else if (!hasExistingItem && item.comboSurplusNum > item.selectedNum) {
      console.log('++Item')
      parasmsList.value.push({
        id: item.id,
        comboId: item.comboId,
        comboNum: ++item.selectedNum,
        comboName: item.comboName,
      })
    }
  } else {
    if (!item.selectedNum) return
    parasmsList.value.forEach((ev) => {
      ev.id === item.id ? (ev.comboNum--, item.selectedNum--) : null
    })
  }
}

onLoad((ev) => {
  if (!memberStore.token) return
  console.log('onLoad', ev)
  let item: any = extractQueryParams(decodeURIComponent(ev?.q))
  if (!item || Object.keys(item).length === 0) {
    console.log('进入新用户处理', item)
    item = extractQueryParams(decodeURIComponent(decodeURIComponent(ev?.q)))
  }
  console.log(item)
  formParams.value.orderSn = item.orderSn
  formParams.value.type = Number(item.type)
  getList()
})

const getList = async () => {
  const res = await getCodeOrdersApi(formParams.value.orderSn)
  if (res.data && res.code === 200) {
    list.value = res.data?.enterpriseOrderDetails.map((item: any) => {
      return {
        ...item,
        selectedNum: 0,
      }
    })
    formParams.value.enterpriseId = res.data?.enterpriseId
    formParams.value.enterpriseName = res.data?.enterpriseName
  } else {
    Toast(res.msg)
  }
}

onReady(() => {
  if (!memberStore.token) BjsPopupRef.value?.open()
})
const submit = () => {
  if (!memberStore.token) return BjsPopupRef.value?.open()
  parasmsList.value = parasmsList.value.filter((ev) => ev.comboNum !== 0)
  console.log('submit', parasmsList.value)
  formRef.value.validate().then(async () => {
    const params = {
      enterpriseId: formParams.value.enterpriseId,
      remark: formParams.value.remark,
      orderSn: formParams.value.orderSn,
      enterpriseOrderCombos: parasmsList.value,
    }
    const res = await postCodeOrderApi(params)
    if (res && res.code === 200) {
      PageSkip('/pages/goods/goods', 'reLaunch')
    } else {
      Toast(res.msg)
      getList()
    }
  })
}
const onback = () => {
  PageSkip('/pages/index/index', 'reLaunch')
}
</script>
<template>
  <view class="img_container" :style="{paddingTop: phoneStore.phoneInfo!.top + 32 + 'px'}">
    <image class="_img" src="/static/images/Frame-288761.png" mode="scaleToFill" />
    <view>美味健康尽在麦德范</view>
  </view>
  <uni-forms
    class="uni-forms"
    ref="formRef"
    :model="formParams"
    :rules="rules"
    label-position="top"
  >
    <uni-forms-item
      :label="`您入${formParams.type === 1 ? '职' : '住'}的${enterpriseObj.enterpriseName}`"
      name="enterpriseName"
    >
      <uni-easyinput
        v-model.trim="formParams.enterpriseName"
        :inputBorder="false"
        disabled
        primaryColor="#8ADF4B"
      ></uni-easyinput>
    </uni-forms-item>
    <uni-forms-item :label="`您的${enterpriseObj.remark}`" name="remark">
      <uni-easyinput
        v-model.trim="formParams.remark"
        :inputBorder="false"
        type="digit"
        :placeholder="`请输入您的${enterpriseObj.remark}`"
        primaryColor="#8ADF4B"
      ></uni-easyinput>
    </uni-forms-item>
  </uni-forms>
  <scroll-view
    scroll-with-animation
    scroll-anchoring
    show-scrollbar
    scroll-x
    class="scroll_container"
    v-if="list.length"
  >
    <view class="_item" v-for="item in list" :key="item.id">
      <view class="_imgBox">
        <image class="package_img" :src="item.thumb" mode="scaleToFill" />
        <view class="maskLayer">{{ item.comboName }}</view>
      </view>
      <view class="_inventory"
        >剩余：<text class="_parts">{{ item.comboSurplusNum || 0 }}</text>
        份
      </view>
      <view class="addSubtractBox">
        <view class="add" @tap="changeValue(item, false)">-</view>
        <view class="_number">{{ item.selectedNum || 0 }}</view>
        <view class="subtract" @tap="changeValue(item, true)">+</view>
      </view>
    </view>
  </scroll-view>
  <view class="no_data" v-else>
    <image
      src="/static/images/2.png"
      mode="scaleToFill"
      class="no_img"
      v-for="item in 3"
      :key="item"
    >
    </image>
  </view>
  <view style="display: flex; margin-top: 82rpx">
    <button class="_cancel" hover-class="view-hover" @click="onback">取消</button>
    <button
      class="_submit"
      type="default"
      :disabled="_disabled"
      hover-class="view-hover"
      @click="submit"
    >
      提交
    </button>
  </view>
  <BjsPopup ref="BjsPopupRef" :enterprise="1" />
</template>
<style lang="scss">
page {
  background: linear-gradient(180deg, #e3fdea 14.57%, #f5f5f5 95.06%);
}
.img_container {
  width: 100%;
  text-align: center;
  color: var(--FontColor-light-50, rgba(0, 0, 0, 0.5));
  font-size: 28rpx;
  ._img {
    width: 180rpx;
    height: 180rpx;
    margin-bottom: 34rpx;
  }
}
.uni-forms {
  margin: 100rpx 0 68rpx;
  width: 100%;
  padding: 0 60rpx;
}
.scroll_container {
  width: 100vw;
  height: 360rpx;
  white-space: nowrap;
  display: flex;
  ._item {
    display: inline-block;
    width: 212rpx;
    min-height: 350rpx;
    margin-right: 28rpx;

    ._imgBox {
      // background-image: url('/static/images/eat_food_bg.png');
      background-size: cover; /* 设置背景图大小适应容器 */
      background-position: center; /* 设置背景图位置居中 */
      position: relative;
      width: 212rpx;
      height: 212rpx;
      border-radius: 13rpx;
      display: flex;
      justify-content: center;
      .maskLayer {
        position: absolute;
        bottom: 0;
        left: 0;
        height: 56rpx;
        line-height: 56rpx;
        width: 100%;
        border-radius: 0 0 13rpx 13rpx;
        background-color: rgba(0, 0, 0, 0.25);
        color: #fff;
        font-size: 24rpx;
        text-align: center;
      }
      .package_img {
        margin-top: 70rpx;
        width: 164rpx;
        height: 100rpx;
      }
    }
    ._inventory {
      margin: 24rpx 0;
      text-align: center;
      letter-spacing: -1px;
      ._parts {
        color: #f53232;
      }
    }
  }
  ._item:first-child {
    margin-left: 28rpx;
  }
}
.no_data {
  display: flex;
  justify-content: space-evenly;
  .no_img {
    width: 212rpx;
    height: 212rpx;
    border-radius: 13rpx;
  }
}
._cancel {
  width: 212rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  color: #000;
  border-radius: 124rpx;
  background: #e9e9e9;
}
._submit {
  width: 408rpx;
  height: 80rpx;
  line-height: 80rpx;
  color: #fff;
  font-size: 32rpx;
  background: #8adf4b;
  border-radius: 124rpx;
}
.addSubtractBox {
  display: flex;
  align-items: center;
  width: 176rpx;
  height: 50rpx;
  background: #fff;
  color: #000;
  border-radius: 16rpx;
  border: 1px solid #e6e6e6;
  margin: 0 auto;
  ._number {
    width: 84rpx;
    height: 100%;
    border-left: 1px solid #e6e6e6;
    border-right: 1px solid #e6e6e6;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .add,
  .subtract {
    flex: 1;
    text-align: center;
    height: 50rpx;
    line-height: 46rpx;
  }
}
::v-deep .uni-easyinput__content-input {
  font-size: 34rpx !important;
  padding-left: 40rpx !important;
  color: #000 !important;
}
::v-deep .uni-forms-item__label {
  min-width: 200rpx !important;
  font-size: 30rpx !important;
}
::v-deep .uni-forms-item {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1) !important;
}
::v-deep .uni-forms-item__error {
  padding-left: 40rpx !important;
}
::v-deep .uni-easyinput__content {
  background-color: transparent !important;
}
// ::v-deep button[disabled][type='default'] {
//   background-color: lighten(#8adf4b, 20%);
//   color: #fff;
// }
// ::v-deep button[type='default'] {
//   background-color: #8adf4b;
//   color: #fff;
// }
</style>
